//
//  Lib.m
//  TripLog
//
//  Created by Administrator on 4/13/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "Lib.h"

const NSString *emailRegEx =
@"(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}"
@"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"
@"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-"
@"z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"
@"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
@"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"
@"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";
const NSString *numberRegEx = @"[0-9]+";

@interface NSString (Utilities)
- (BOOL) isEmail;
@end

@implementation NSString (Utilities)
- (BOOL) isEmail {
	NSPredicate *regExPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx];
	return [regExPredicate evaluateWithObject:self];
}
@end


static NSMutableDictionary* settings;
static NSString* _dbFilePath = nil; 
@implementation Lib
+(NSString*)docDirPath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return [paths objectAtIndex:0];
}

+(NSString*)dbFilePath {
    if (!_dbFilePath){
        NSArray *pathsToDocuments = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        NSString *documentsDirectory = [pathsToDocuments objectAtIndex:0];
        
        NSString *yourNewDatabasePath = [documentsDirectory stringByAppendingPathComponent:@"db.sqlite"];
        
        if (![[NSFileManager defaultManager] fileExistsAtPath:yourNewDatabasePath]) {
            
            NSString *pathsToResources = [[NSBundle mainBundle] resourcePath];
            NSString *yourOriginalDatabasePath = [pathsToResources stringByAppendingPathComponent:@"db.sqlite"];
            if ([[NSFileManager defaultManager] copyItemAtPath:yourOriginalDatabasePath toPath:yourNewDatabasePath error:NULL]){
                _dbFilePath = [yourNewDatabasePath retain];
            }
            
        } else{
            _dbFilePath = [yourNewDatabasePath retain];
        }

    }
    //NSLog(@"%@",_dbFilePath);
    return _dbFilePath;
}

+(void)showAlert:(NSString*)title withMessage:(NSString*)msg {
    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:title
                                                        message:msg 
                                                       delegate:nil 
                                              cancelButtonTitle:@"Ok" 
                                              otherButtonTitles:nil];
    [alertView show];
}


+(id)getValueOfKey:(NSString*)key {	
	if (!settings) {
		settings = [[[NSUserDefaults standardUserDefaults] objectForKey:@"Blindfate.settings"] retain];
		if (!settings) {
			settings = [[NSMutableDictionary alloc] init];
		}
	}
	if ([settings objectForKey:key]) {
		return [settings objectForKey:key];
	}
	
	return nil;
}
+(void)setValue:(id)value ofKey:(NSString*)key {
	if (!settings) {
		settings = [[[NSUserDefaults standardUserDefaults] objectForKey:@"Blindfate.settings"] retain];
		if (!settings) {
			settings = [[NSMutableDictionary alloc] init];
		}
	}
    if (value) {
        [settings setObject:value forKey:key];        
    } else {
        [settings removeObjectForKey:key];
    }
    
	[[NSUserDefaults standardUserDefaults] setObject:settings forKey:@"Blindfate.settings"];
	[[NSUserDefaults standardUserDefaults] synchronize];
}

+ (void)showLoadingViewOn2:(UIView *)aView withAlert:(NSString *)text{
	
	UIView *loadingView = [[UIView alloc] init];
	loadingView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleBottomMargin|
	UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleWidth;
	loadingView.frame = ([Lib isIphone])?CGRectMake(0, 0, aView.frame.size.width, aView.frame.size.height):CGRectMake(0, 0, aView.frame.size.width, aView.frame.size.height-80);
	loadingView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.0];
	loadingView.tag = 1011;
	UILabel *loadingLabel = [[[UILabel alloc ] init] autorelease];
	
	UIView* roundedView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 80)];
	roundedView.center = CGPointMake(loadingView.frame.size.width/2, loadingView.frame.size.height/2);
	roundedView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8];
	roundedView.layer.borderColor = [UIColor clearColor].CGColor;
	roundedView.layer.borderWidth = 1.0;
	roundedView.layer.cornerRadius = 10.0;
	[loadingView addSubview:roundedView];
	roundedView.autoresizingMask = loadingLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;
	
	loadingLabel.text = text;
	loadingLabel.frame = CGRectMake(roundedView.frame.origin.x, roundedView.frame.origin.y + 50, 200, 30);
	//loadingLabel.adjustsFontSizeToFitWidth = YES;
	loadingLabel.textAlignment = UITextAlignmentCenter;
	loadingLabel.font = [UIFont boldSystemFontOfSize:14];	
	loadingLabel.backgroundColor = [UIColor clearColor];
	loadingLabel.textColor = [UIColor whiteColor];
	[loadingView addSubview:loadingLabel];
	
	UIActivityIndicatorView *activityIndication = [[[UIActivityIndicatorView alloc] init] autorelease];
	activityIndication.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
	activityIndication.frame = CGRectMake((loadingView.frame.size.width - 30)/2,
										  roundedView.frame.origin.y + 15,
										  30,
										  30);
	
	[activityIndication startAnimating];	
	[loadingView addSubview:activityIndication];
	activityIndication.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;

	//	[activityIndication release];
	[aView addSubview:loadingView];
	[loadingView release];
}

+ (BOOL)checkInternetConnection {
	Reachability *reachInternet = [Reachability reachabilityForInternetConnection];
	[reachInternet startNotifier];
	
	NetworkStatus res = [reachInternet currentReachabilityStatus];
	[reachInternet stopNotifier];
	
	return !(res == NotReachable);
}

+ (void)removeLoadingViewOn:(UIView *)superView{
	for (UIView *aView in superView.subviews) {
		if ((aView.tag == 1011)  && [aView isKindOfClass:[UIView class]]) {
			[aView removeFromSuperview];
		}
	}
}


+ (void)showIndicatorViewOn2:(UIView *)aView{
	
	UIActivityIndicatorView *activityIndication = [[UIActivityIndicatorView alloc] init];
	activityIndication.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
	int width = [Lib isIphone]?20:30;
	activityIndication.frame = CGRectMake((aView.frame.size.width - width)/2,
										  (aView.frame.size.height-width)/2,
										  width,
										  width);
	
	activityIndication.tag = 1012;
	[activityIndication startAnimating];	
	activityIndication.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;
	
	
	[aView addSubview:activityIndication];
	[activityIndication release];
}

+ (void)removeIndcatorViewOn:(UIView *)superView {
	for (UIView *aView in superView.subviews) {
		if ((aView.tag == 1012)  && [aView isKindOfClass:[UIActivityIndicatorView class]]) {
			[aView removeFromSuperview];
		}
	}
}


+(NSDate*)getThisWeek {
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents* components = [cal components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:[[[NSDate alloc] init]autorelease]];
    
    [components setDay:([components day] - ([components weekday] - 1))]; 
    NSDate *thisWeek  = [cal dateFromComponents:components];
    
//    [components setDay:([components day] - 7)];
//    NSDate *lastWeek  = [cal dateFromComponents:components];
//    
//    [components setDay:([components day] - ([components day] -1))]; 
//    NSDate *thisMonth = [cal dateFromComponents:components];
//    
//    [components setMonth:([components month] - 1)]; 
//    NSDate *lastMonth = [cal dateFromComponents:components];
//    
//    NSLog(@"today=%@",today);
//    NSLog(@"yesterday=%@",yesterday);
//    NSLog(@"%@",thisWeek);  
    //    NSLog(@"lastWeek=%@",lastWeek);
//    NSLog(@"thisMonth=%@",thisMonth);
//    NSLog(@"lastMonth=%@",lastMonth);
    return thisWeek;
}

+(NSDate*)getThisMonth {
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents* components = [cal components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:[[[NSDate alloc] init]autorelease]];
    
    [components setDay:([components day] - ([components day] -1))]; 
    NSDate *thisMonth = [cal dateFromComponents:components];
        
    //    [components setMonth:([components month] - 1)]; 
    //    NSDate *lastMonth = [cal dateFromComponents:components];
    //    
    //    NSLog(@"today=%@",today);
    //    NSLog(@"yesterday=%@",yesterday);
    //    NSLog(@"lastWeek=%@",lastWeek);
//    NSLog(@"thisMonth=%@",thisMonth);
    //    NSLog(@"lastMonth=%@",lastMonth);
    return thisMonth;
}

+(NSDate*)getLastMonth {
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents* components = [cal components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:[[[NSDate alloc] init]autorelease]];
    
    [components setDay:([components day] - ([components day] -1))];
    [components setMonth:([components month] - 1)]; 
    NSDate *lastMonth = [cal dateFromComponents:components];
    //    
    //    NSLog(@"today=%@",today);
    //    NSLog(@"yesterday=%@",yesterday);
    //    NSLog(@"lastWeek=%@",lastWeek);
    //NSLog(@"thisMonth=%@",thisMonth);
//    NSLog(@"lastMonth=%@",lastMonth);
    return lastMonth;
}
+(BOOL)isIphone {
    //NSString *deviceType = [UIDevice currentDevice].model;
    //return [deviceType isEqualToString:@"iPhone"];
    return !(UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPad);
}
+ (void)customWebview : (UIWebView *)aWebView {
	// tranparent WebView
	aWebView.opaque = NO;
	aWebView.backgroundColor = [UIColor clearColor];
	// web view
	id scroller = [aWebView.subviews objectAtIndex:0];
	
	for (UIView *subView in [scroller subviews])
		if ([[[subView class] description] isEqualToString:@"UIImageView"])
			subView.hidden = YES;
    
}

+(void)saveString:(NSString*)_str forKey:(NSString*)_key {
	NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
	[prefs setObject:_str forKey:_key];
	[prefs synchronize];
}

+(NSString*)getStringForKey:(NSString*)_key {
	return [[NSUserDefaults standardUserDefaults] stringForKey:_key];
	
}

+(UIImage*)loadingImageFromFile:(NSString*)fileName fileExtension:(NSString*) fileExtension{
	NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:fileExtension];
	UIImage *image = [[UIImage alloc] initWithContentsOfFile:filePath];
	return [image retain];
}

+(NSString*)optimizeResultString:(NSString*)inputString{
	char temp;
	int count = 0;
	for (int i = [inputString length]-1; i>0; i--) {
		temp = [inputString characterAtIndex:i];
		if (temp == '0' || temp == '.') {
			count ++; 
			if (temp == '.') {
				break;
			}
		}
		else {
			break;
		}
	}		
	
	return [inputString substringToIndex:[inputString length] - count];;
}

+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
    UIGraphicsEndImageContext();
    return newImage;
}

+ (void) insertView:(UIView*) addView intoView:(UIView*)parentView{
	CATransition *animation = [CATransition animation];
	[animation setDuration:0.5];
	[animation setType:kCATransitionPush];
	[animation setSubtype:kCATransitionFromRight];
	
	[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
	[[parentView layer] addAnimation:animation forKey:@"SwitchToView"];
	[[addView layer] addAnimation:animation forKey:@"SwitchToView"];		
	
	[parentView addSubview:addView];	
}

+ (void) removeView:(UIView*) rView fromView:(UIView*)parentView{
	CATransition *animation = [CATransition animation];
	[animation setDuration:0.5];
	[animation setType:kCATransitionPush];
	[animation setSubtype:kCATransitionFromLeft];
	
	[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
	[[parentView layer] addAnimation:animation forKey:@"SwitchToView"];
	[[rView layer] addAnimation:animation forKey:@"SwitchToView"];		
	
	[rView removeFromSuperview];	
}

+ (NSString*) stringWithUUID {
	CFUUIDRef	uuidObj = CFUUIDCreate(nil);//create a new UUID
	//get the string representation of the UUID
	NSString	*uuidString = (NSString*)CFUUIDCreateString(nil, uuidObj);
	CFRelease(uuidObj);
	return [uuidString autorelease];
}

+ (NSString*) stringWithUUIDWithoutSeprate{
	return [[[Lib stringWithUUID] stringByReplacingOccurrencesOfString:@"-" withString:@""] retain];	
}

@end
































